import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import com.sleepycat.bind.EntryBinding;
import com.sleepycat.bind.serial.SerialBinding;
import com.sleepycat.bind.tuple.TupleBinding;
import com.sleepycat.je.DatabaseEntry;
import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.Transaction;



public class MIMOPut {
	private static File dir = new File("./DATA"); 
	private static File datesFile;
	private static File[] files;
	private static BerkeleyDBWrapper wrapper;
	
	public MIMOPut() throws DatabaseException, FileNotFoundException{
		wrapper = new BerkeleyDBWrapper("./DB"); 
		files= dir.listFiles(); // THIS WILL NEED TO BE CHANGED FOR SUBDIRECTORIES, FILES SHOULD CONTAIN A FULL LIST
		datesFile = new File("./DATES.csv");
	}

	public static void main(String args[]){
		try {
			MIMOPut m=new MIMOPut();
		} catch (DatabaseException e) {
			System.out.println("Problem with Database");
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			System.out.println("DB directory not found");
			e.printStackTrace();
		}
		loadDates();
	//	loadMetrics();		
		String testDate = wrapper.getDBArrayListVal("dates").get(1);
	}
	
	private static void loadMetrics(){
		for(int i=0;i<files.length;i++){
			File current = files[i];
			String compare = current.toString();
			if(!compare.contains("svn")){
				String currentName = current.toString();
				String ticker = currentName.substring(currentName.lastIndexOf('\\')+1, currentName.indexOf('-'));
				String metric = currentName.substring(currentName.indexOf('-')+1,currentName.indexOf('('));
				String startDate = currentName.substring(currentName.indexOf('(')+1, currentName.indexOf(','));
				String endDate = currentName.substring(currentName.indexOf(',')+1,currentName.indexOf(')'));
				List<String[]> readIn=loadFile(current,2);
				System.out.println("Now loading metric File " +files[i].toString()+"...");
				int counter = 0;
				System.out.print("Percent Complete: ");
				for(int j=0;j<readIn.size();j++){
					double dprogress = 100*j/readIn.size();
					int progress= (int)dprogress;
					if(progress != counter){
						System.out.print(progress +" ");
						counter=progress;
					}
					String[] dataArray = readIn.get(j);
					String key = ticker+"-"+metric+"-"+dataArray[0];
					wrapper.putDBSimpleVal(key,dataArray[1]);
				}
				System.out.println("\nSuccessfully inputted File " + files[i].toString());
				System.out.println();
			}
		}
	}
	
	private static void loadDates(){
		ArrayList<String> dateList = new ArrayList<String>();
		List<String[]> listTemp = loadFile(datesFile,1);
		System.out.println("Now loading date data from " +datesFile.toString()+"...");
		int counter =0;
		System.out.print("Percent Complete: ");
		for(int i =0;i<listTemp.size();i++){
			double dprogress = 100*i/listTemp.size();
			int progress= (int)dprogress;
			if(progress != counter){
				System.out.print(progress+" ");
				counter=progress;
			}
			String[] tempString = listTemp.get(i);
			dateList.add(i, tempString[0]);
			wrapper.putDBObjVal("dates", dateList);
		}
		System.out.println("\nSuccessfully inputted date data from " +datesFile.toString());
		System.out.println();
	}
	
    private static List<String[]> loadFile(File theFile, int numFields) {
        List<String[]> records = new ArrayList<String[]>();
        try {
            String theLine = null;
            FileInputStream fis = new FileInputStream(theFile);
            BufferedReader br = new BufferedReader(new InputStreamReader(fis));
            while((theLine=br.readLine()) != null) {
                String[] theLineArray = theLine.split(",");
                if (theLineArray.length != numFields) {
                    System.out.println("Malformed line found in " + theFile.getPath());
                    System.out.println("Line was: '" + theLine);
                    System.out.println("length found was: " + theLineArray.length);
                    System.exit(-1);
                }
                records.add(theLineArray);
            }
            // Close the input stream handle
            fis.close();
        } catch (FileNotFoundException e) {
            System.err.println(theFile.getPath() + " does not exist.");
            e.printStackTrace();
        } catch (IOException e)  {
            System.err.println("IO Exception: " + e.toString());
            e.printStackTrace();
            System.exit(-1);
        }
        return records;
    }
}
